<?php
/**
 * 登录控制器
 *
 * @author Fong.zhang
 */
namespace Home\Controller;

use Think\Controller;

class LoginController extends Controller
{
    public function indexAction() {
        $access = false;
        $error = '';

        if (IS_POST) {
            $admin_model = D('Admin');

            $email = I('post.email');
            $password = I('post.password');
            $captcha = I('post.captcha');

            $verify = new \Think\Verify();
            if (!$verify->check($captcha)) {
                $this->ajaxReturn(array(
                    'error' => L('ERROR_CAPTCHA')
                ));
            };

            $admin_condition = array(
                'email' => $email,
                'password' => md5($password),
                'is_deleted' => '0'
            );

            $access = $admin_model->where($admin_condition)->find();

            if ($access) {
                $server_pool = array(
                    'http://123.57.22.77'
                );

                foreach ($server_pool as $server) {
                    $post_data = array (
                        'Login' => 1,
                        "uemail" => $email,
                        "upasswd" => $password
                    );

                    $ch = curl_init();

                    curl_setopt($ch, CURLOPT_URL, $server);
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                    // post数据
                    curl_setopt($ch, CURLOPT_POST, 1);
                    // post的变量
                    curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

                    $output = curl_exec($ch);
                    curl_close($ch);

                    $user = json_decode($output, true);

                    if (!$user['error']) {
                        session('user_id', $user['user_id']);
                        session('sso_session_key', $user['sso_session_key']);
                    }
                }
            } else {
                $error = 'LOGIN FAILED';
            }

            $this->ajaxReturn(array(
                'error' => $error
            ));
        }

        $this->display('index/index');
    }
}